package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class DeliverUtil {
	/*
	 * 
	 * com   快递公司编号
	 * no    快递编号
	 */
	//获取快递信息URL
	public static String deliverPostUrl = "http://poll.kuaidi100.com/poll/query.do";
	//获取快递公司
	public static String getDeliverCompanyUrl = "http://www.kuaidi100.com/autonumber/auto";
	//
	public static String deliverCustomer = "A540959A7586ECEC47B80997F0E4DC49";
	
	public static String deliverKey = "gxBcWyBz7685";
	
	public static JSONObject getDeliverMsg(String com,String no){
		String key = "b8051696982674fcf93198ea1795adcd";
		String dtype = "json";
		JSONObject jsonResult = null;
		String url = "http://v.juhe.cn/exp/index?key="+key+"&com="+com+"&no="+no+"&dtype"+dtype;
	        try {
	        	DefaultHttpClient client = new DefaultHttpClient();
	            //发送get请求
	            HttpGet request = new HttpGet(url);
	            HttpResponse response = client.execute(request);
	 
	            /**请求发送成功，并得到响应**/
	            	if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	            	
	                /**读取服务器返回过来的json字符串数据**/
	                String strResult = EntityUtils.toString(response.getEntity());
	                System.out.println(strResult);
	                /**把json字符串转换成json对象**/
	                if(strResult!=null){
	                	
	                	jsonResult = JSONObject.parseObject(strResult);
	                }else{
	                	
	                	jsonResult = new JSONObject();
	                }
	                
	                url = URLDecoder.decode(url, "UTF-8");
	            	}
	        }catch(Exception e){
	            	
	        }
	    return jsonResult;
	}
	//快递100
	public static JSONObject getDeliverMsg(String com,String no,String company_name){
		JSONObject jsonResult = null;
		JSONObject obj  = new JSONObject();
		obj.put("com", com);
		obj.put("num", no);
		String param =obj.toJSONString();
		String customer =deliverCustomer;
		String key = deliverKey;
		String sign =MD5Util.MD5Encode(param+key+customer,"UTF-8").toUpperCase();
		String sendParams = "param="+param+"&sign="+sign+"&customer="+customer;
		jsonResult = JSON.parseObject(HttpRequest(deliverPostUrl,HttpMethod.POST,"",sendParams));
		System.out.println(jsonResult.toJSONString());
		JSONObject deliverRet = new JSONObject();
		if("ok".equals(jsonResult.get("message"))){
			JSONArray jsonArray = JSON.parseArray(jsonResult.get("data").toString());
			JSONArray jsonRetArray = new JSONArray();
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject objlist = JSON.parseObject(jsonArray.get(i).toString());
				JSONObject retObj = new JSONObject();
				retObj.put("datetime", objlist.get("ftime"));
				retObj.put("remark", objlist.get("context").toString());
				retObj.put("zone", "");
				jsonRetArray.add(retObj);
			}
			JSONObject resultObj = new JSONObject();
			resultObj.put("com", com);
			resultObj.put("company",company_name);
			resultObj.put("no", no);
			resultObj.put("status", "1");
			resultObj.put("list", jsonRetArray);
			
			deliverRet.put("error_code", 0);
			deliverRet.put("reason", "成功的返回");
			deliverRet.put("resultcode", "200");
			deliverRet.put("error_code", 0);
			deliverRet.put("result", resultObj);
		}else{
			deliverRet.put("resultcode", "201");
		}
		return deliverRet;
	}
	
	
	public static void main(String[] args) {
	
		JSONObject deliver = DeliverUtil.getDeliverMsg("tiantian","550632533333","申通快递");
		
		System.out.println(deliver.toJSONString());
		
	/*	String param = "id=gxBcWyBz7685&com="+"yuantong"+"&nu="+"886143417497818362"+"&show=0&muti=1&order=asc";
		String a = HttpRequest("http://api.kuaidi100.com/api",HttpMethod.GET,"",param);
		System.out.println(a);*/
		//http://api.kuaidi100.com/api?id=gxBcWyBz7685&com=yuantong&nu=886143417497818362&show=0&muti=1&order=asc
		//http://api.kuaidi100.com/api/?id=gxBcWyBz7685&com=yuantong&nu=886143417497818362&show=0&muti=1&order=asc
	}
	
	
	public static String HttpRequest(String path, HttpMethod method, String headerParams, String bodyParams) {
		String re = "";
		try {
			URI uri = new URI(path);
			SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
			
			if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.GET.equals(method)) {
				uri = new URI(uri.toString()+"?"+bodyParams);
			}
			
			ClientHttpRequest chr = schr.createRequest(uri, method);

			HttpHeaders headers = chr.getHeaders();
			if (headerParams != null && !"".equals(headerParams)) {
				System.out.println(headerParams);
				String[] pList = headerParams.split("&");
				for (String p : pList) {
					String[] entry = p.split("=");
					headers.set(entry[0], entry[1]);
				}
			}
			
			if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.POST.equals(method)) {
				chr.getBody().write(bodyParams.getBytes());// body中设置请求参数
			}
			ClientHttpResponse res = chr.execute();
			InputStream is = res.getBody(); // 获得返回数据,注意这里是个流
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String str = "";
			while ((str = br.readLine()) != null) {
				re += str;
			}
		//	System.out.println(re);// 获得页面内容或返回内容
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return re;
	}
	
	
}
